<?php
namespace Home\Controller;
use Think\Controller;
use Think\Cache\Driver\Redis;
class CallUrlController extends Controller {
	public function __construct ()
	{
		parent::__construct();
	}
	public function news(){
		$mod = D('sucai');
		$data = $mod->where(array('id'=>I('id','','base64_decode')))->field('title,content')->find();
		$this->assign('data',$data);
		$this->display();
	}
	public function index()
	{
		$redis = new Redis();
		$redis->hset('tc',date('Y-m-d H:i:s'),file_get_contents('php://input'));
		/* 加载微信SDK */
		import('@.Util.ThinkWechat');
		$weixin = new \ThinkWechat(I('get.token'));
	
		/* 获取请求信息 */
		$data = $weixin->request();
	
		/* 获取回复信息 */
		list($content, $type) = $this->reply($data,$redis);
		
		/* 响应当前请求 */
		$weixin->response($content, $type);
	}
	
	private function reply($data,&$redis)
	{
		if('text' == $data['MsgType'])
		{	//文本消息处理
			$reply = $this->auto_reply($data,$redis);
			$this->save($data);
		} 
		elseif('image' == $data['MsgType'])
		{	//图片消息处理
			$reply = array('暂不支持图片消息', 'text');
			$this->save($data);
		} 
		elseif('voice' == $data['MsgType'] && ''!=$data['Recognition'])
		{	//语音消息处理
			$reply = array($data['Content'], 'text');
			$this->save($data);
		}
		elseif('voice' == $data['MsgType'])
		{	//语音消息处理
			$reply = array('未识别语音消息', 'text');
			$this->save($data);
		}
		elseif('video' == $data['MsgType'])
		{	//视频消息处理
			$reply = array('暂不支持图片消息', 'text');
			$this->save($data);
		}
		elseif('location' == $data['MsgType'])
		{	//地理位置消息处理
			exit;
		}
		elseif('link' == $data['MsgType'])
		{	//链接消息处理
			exit;
		}
		elseif('event' == $data['MsgType'] && 'subscribe' == $data['Event'] && '' != $data['EventKey'])
		{	//带参数的二维码初次扫描
			$this->qrcode_cont($data,0,$redis);
			exit;
		}
		elseif('event' == $data['MsgType'] && 'subscribe' == $data['Event'])
		{	//订阅处理
			$welcomes = D('App')->where(array('username'=>$data['ToUserName']))->getField('welcomes');
			$reply = array($welcomes, 'text');
		} 
		elseif('event' == $data['MsgType'] && 'unsubscribe' == $data['Event'])
		{	//取消订阅
			exit;
		}
		elseif('event' == $data['MsgType'] && 'SCAN' == $data['Event'])
		{	//带参数的二维码扫描.
			$this->qrcode_cont($data,1,$redis);
			exit;
		}
		elseif('event' == $data['MsgType'] && 'CLICK' == $data['Event'])
		{	//点击菜单拉取消息时的事件推送
			exit;
		}
		elseif('event' == $data['MsgType'] && 'VIEW' == $data['Event'])
		{	//点击菜单跳转链接时的事件推送
			exit;
		}
		else
		{
			exit;
		}
		return $reply;
	}
	//自动回复
	private function auto_reply(&$data,$redis){
		$mod = D('Keyword');
		$key = $mod->where(array('word'=>trim($data['Content'])))->getField('id,sid');
		if(!empty($key)){
			$data = D('sucai')->where(array('id'=>$key['sid']))->select();
			foreach ($data as $k=>&$v){
				$return[$k]['Title']= $v['title'];
				$return[$k]['Description']= $v['abstract '];
				$return[$k]['PicUrl']= $_SERVER['HTTP_HOST'].'/Uploads/'.$v['cover'];
				$return[$k]['Url']= $_SERVER['HTTP_HOST'].'/CallUrl/'.base64_encode($v['id']);
			}
			$mod->where(array('id'=>$key['id']))->setInc('count');
			return array($return,'news');
		}
		return array('未识别消息！','text');
	}
	//二维码统计
	private function qrcode_cont(&$data,$type,&$redis){
		if(!$redis->get($data['ToUserName'].$data['FromUserName'].$data['EventKey'].$type)){
			$data['app_id'] = D('App')->where(array('username'=>$data['ToUserName']))->getField('id');
			$data['openid'] = $data['FromUserName'];
			$data['scene_id'] = str_replace('qrscene_', '', $data['EventKey']);
			$data['addtime'] = $data['CreateTime'];
			$data['type'] = $type;
			D('Qr_code_count')->add($data);
			$redis->set($data['ToUserName'].$data['FromUserName'].$data['EventKey'].$type, $data['CreateTime'],3);
		}
	}
	//保存消息
	private function save($data){
		$data['app_id'] = D('App')->where(array('username'=>$data['ToUserName']))->getField('id');
		$data['openid'] = $data['FromUserName'];
		$mod = D('message');
		$data = $mod->create($data);
		$mod->add($data);
	}
        
                public function checkSafe(){
                                    $echoStr = $_GET["echostr"];
                                    
                                    if($this->checkSignature()){
                                        echo $echoStr;
                                        exit;
                                    }
                }
        
                private function checkSignature() {
                                    $signature = $_GET["signature"];
                                    $timestamp = $_GET["timestamp"];
                                    $nonce = $_GET["nonce"];

                                    $token =C("TOKEN");
                                    $tmpArr = array($token, $timestamp, $nonce);
                                    sort($tmpArr, SORT_STRING);
                                    $tmpStr = implode($tmpArr);
                                    $tmpStr = sha1($tmpStr);
                                      
                                    if ($tmpStr == $signature) {
                                        return true;
                                    } else {
                                        return false;
                                    }
              }

}